import scrapy


class QingtingSpider(scrapy.Spider):
    name = "qingting"
    allowed_domains = ["qtfm.cn"]
    start_urls = ["https://m.qtfm.cn/rank/"]

    def parse(self, response):
        a_list = response.xpath("//div[@class='rank-list']/a")
        for a in a_list:
            id = a.xpath("./div[@class='badge']/text()").extract_first()
            img_src = a.xpath("./img/@src").extract_first()
            title = a.xpath(".//div[@class='title']/text()").extract_first()
            desc = a.xpath(".//div[@class='desc']/text()").extract_first()
            play_number = a.xpath(".//div[@class='info']/div[1]/span/text()").extract_first()


            # 生成的信息要在管道中处理
            yield {
                'type':'info',
                'id':id,
                'img_src':img_src,
                'title':title,
                'desc':desc,
                'play_number':play_number
            }
            # 生成新的请求对象,会发送到调度器中处理，调度器把请求交给下载器
            # yield scrapy.Request(img_src,callback=self.parse_detail,meta={'title':title})
            yield scrapy.Request(img_src,callback=self.parse_img,cb_kwargs={'title':img_src.split('/')[-1]})


    def parse_img(self,response,title):
        filename = title
        yield {
            'type':'img',
            'filename':filename,
            'img':response.body
        }